package jk.spider.core.impl;

import java.util.ArrayList;
import java.util.List;

import jk.spider.api.event.EventSink;
import jk.spider.mod.plugin.Plugin;
import jk.spider.util.config.ConfigConstants;
import jk.spider.util.config.MappedPropertySet;
import jk.spider.util.config.PropertySet;

import org.apache.log4j.Logger;

public class PluginFactory {
	private static final Logger log = Logger.getLogger(PluginFactory.class);
	public EventSink[] createPlugins(PropertySet props){
		List<EventSink> loadedPlugins = new ArrayList<EventSink>();
		PropertySet pluginsProps = new MappedPropertySet(ConfigConstants.CONFIG_PLUGIN, props);
		int pluginCount = pluginsProps.getInteger(ConfigConstants.PLUGIN_COUNT, 0);
		log.info("Loading " + pluginCount + " plugins.");
		
		for(int i = 0; i < pluginCount; i++) {
			Plugin plugin = null;
			Class pluginClass = pluginsProps.getClass("" + (i+1) + "." +ConfigConstants.PLUGIN_CLASS, null);
			log.info("Loading plugin configuration '" + pluginClass.getName() + "'...");
			if(pluginClass != null) {
				try {
					plugin = (Plugin) pluginClass.newInstance();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			loadedPlugins.add(plugin);	
		}
		log.info("Loaded " + loadedPlugins.size() + " plugins.");
		return (Plugin[]) loadedPlugins.toArray(new Plugin[loadedPlugins.size()]);
	}
}
